/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package main.java.cn.webrx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Project: jse2204 - StudentDemo
 * <p>Powered by webrx On 2022-09-23 14:29:03
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class StudentDemo {
    static String db = "c:/db.dat";

    static {
        if (!new File(db).exists()) {
            try (var oos = new ObjectOutputStream(new FileOutputStream(db))) {
                List<Student> list = new ArrayList<>();
                oos.writeObject(list);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        //Student s1 = new Student(10, "李四", 80);
        //System.out.println(save(s1));
        //List<Student> list = read();
        //Student st = list.get(0);
        //System.out.println(st);
        //System.out.println(st.getName());

        System.out.println(read());

        //Scanner sc = new Scanner(System.in);
        //System.out.print("请输入学生ID");
        //int id = sc.nextInt();
        //System.out.print("请输入学生姓名");
        //String name = sc.next();
        //System.out.print("请输入学生成绩");
        //int score = sc.nextInt();
        //if(save(new Student(id,name,score)) == 1){
        //    System.out.println("保存成功");
        //}



    }

    public static List<Student> read() {
        List<Student> list = new ArrayList<>();
        try (var ois = new ObjectInputStream(new FileInputStream(db))) {
            list = (ArrayList<Student>) ois.readObject();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    public static int save(Student st) {
        int i = 0;
        List<Student> list = read();
        list.add(st);
        try (var oos = new ObjectOutputStream(new FileOutputStream(db))) {
            oos.writeObject(list);
            i = 1;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return i;
    }
}
